#!/usr/bin/python3

import rasover
  

CLIENT_ID="YourClientIDHere"
CLIENT_SECRET="YourClientSecretHere"

APP_TOKEN="YourAppTokenHere"
USER_TOKEN="YourUserTokenHere"  
  
def processMessages(messagesToProcess):
  for i in range (0, len(messagesToProcess)):
    print (messagesToProcess[i]["message"])
    if ("Trigger ABC" in messagesToProcess[i]["message"] ):
      rasover.sendMessage(APP_TOKEN, USER_TOKEN, "Trigger","ABC trigged")
    if ("Trigger XYZ" in messagesToProcess[i]["message"] ):
      rasover.sendMessage(APP_TOKEN, USER_TOKEN, "Trigger","XYZ trigged")


if __name__ == "__main__":
  
  rasover.sendMessage(APP_TOKEN,USER_TOKEN,"test","Test Message")
  
  downloadedAllMessages=False
  while (1==1):
    print ("(re-)establishing connection")
    ws = rasover.openConnection(CLIENT_ID, CLIENT_SECRET)
    
    if (downloadedAllMessages==False):
      rasover.deleteAllMessages(CLIENT_ID, CLIENT_SECRET)
      downloadedAllMessages=True;
      
    print ("waiting for PushOver to send a packet");
    while (1==1):
      result = ws.recv()
      if (result == b'!'):
        print ("message waiting")
        messagesToProcess = rasover.downloadMessages(CLIENT_ID, CLIENT_SECRET)
        processMessages(messagesToProcess)
      if (result == b'#'):
        #print ("Keepalive received")
        pass
      if (result == b'R'):
        print ("Request for reconnect received")
        break
  
